package org.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/demo", asyncSupported = true)
public class AsyncDemoServlet extends HttpServlet {
	
	ExecutorService executor = Executors.newFixedThreadPool(10);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("开始时间：" + new Date() + ".");
		out.flush();

		if (!request.isAsyncSupported()) {
			   System.out.println("the servlet is not supported Async");
			   return;
			}
		
		// 在子线程中执行业务调用，并由其负责输出响应，主线程退出
		final AsyncContext asyncContext = request.startAsync();
		asyncContext.setTimeout(10 * 1000);  
		
		 asyncContext.addListener(new AsyncListener() {
             @Override  
             public void onComplete(AsyncEvent event) throws IOException {  
                 //在这里处理正常结束的逻辑  
            	 final  AsyncContext asyncContext = event.getAsyncContext();
             	PrintWriter out = asyncContext.getResponse().getWriter();
      			out.println("业务 正常结束 onComplete...");
      			out.flush();
            	 
             }  

             @Override  
             public void onTimeout(AsyncEvent event) throws IOException {  
                 //在这里处理超时的逻辑  
            	 AsyncContext asyncContext = event.getAsyncContext();  
                   String uri = (String) asyncContext.getRequest().getAttribute("uri");  
                   Map params = (Map) asyncContext.getRequest().getAttribute("params");  
                   System.out.println("async request timeout, uri : {}, params : {}="+uri+params.toString());  
                   try {
                	     HttpServletResponse resp = (HttpServletResponse) asyncContext.getResponse();  
                         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                       
				} catch (Exception e) {
					// TODO: handle exception
				}finally{
					  asyncContext.complete();  
				}
              
             }  

             @Override  
             public void onError(AsyncEvent event) throws IOException {  
                 //在这里处理出错的逻辑  
             }  
             @Override  
             public void onStartAsync(AsyncEvent event) throws IOException {  
                 //在这里处理开始异步线程的逻辑  
            	
             }  
         }); 
		 
//		CountDownLatch countDownLatch = new CountDownLatch(2);
		
		
		 executor.submit(new CanceledCallable(3000,asyncContext));
		 
		 
		 
//		 asyncContext.start(new Runnable() {  
//             @Override  
//             public void run() {  
//                 //在这里做耗时的操作，如果做完，则调用complete方法通知回调，异步处理结束了
//            	 try {
//            		 	Thread.sleep(3000);
//            			PrintWriter out = asyncContext.getResponse().getWriter();
//             			out.println("业务处理完毕的时间：" + new Date() + ".");
//             			out.flush();
//				} catch (Exception e) {
//					// TODO: handle exception
//				}finally{
//					  asyncContext.complete();  
//				}
//             }
//         });
		 
		

		out.println("结束时间：" + new Date() + ".");
		out.flush();
	}
	
	
}
